package arcon.handlers;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.io.InputStreamReader;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.ui.PlatformUI;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;

import backboneCode.*;

/**
 * Our sample handler extends AbstractHandler, an IHandler base class.
 * @see org.eclipse.core.commands.IHandler
 * @see org.eclipse.core.commands.AbstractHandler
 */
public class ArConHandler extends AbstractHandler {
	
	ConsoleCode internalConsole = new ConsoleCode();
	WildCardStringFinder finder = new WildCardStringFinder();
	
	//private URI typesUri = null;
	
	/**
	 * The constructor.
	 */
	public ArConHandler() {
		
	}

	/**
	 * the command has been executed, so extract extract the needed information
	 * from the application context.
	 */
	public Object execute(ExecutionEvent event) throws ExecutionException {
		
		GlobalStorage.setModelFlag(-2);
		ISelection selection = 
			PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getSelection();
		if (selection == null) {
			/* Tell user that no project is selected, and ask them to select
			 * the project that should be validated.
			 */
			internalConsole.reciveCall(3, "A project wasn't selected!");
			return null;			
		}
		IResource res = extractSelection(selection);
		
		IWorkspaceRoot myWorkspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
		IProject umlProject = myWorkspaceRoot.getProject(res.getName());
		String umlProjectPath =  umlProject.getLocation().makeAbsolute().toString();
		
		File projectDirectory = new File(umlProjectPath); 
		FileFilter dirFilter = new FileFilter() {
			public boolean accept(File file) {
				return file.isDirectory();
			}
		};
		
		File[] projectSubDirectories = projectDirectory.listFiles(dirFilter);
		
		findUMLFiles(projectSubDirectories);
		
		int check = GlobalStorage.getModelFlag();
		if (check != 1) {
			if (check == -1)
				internalConsole.reciveCall(3, "Couldn't find the system model");
			else if (check == 0)
				internalConsole.reciveCall(3, "Couldn't find the architecture model");
			else
				internalConsole.reciveCall(3, "Couldn't find the any model");
		} else if (check == 1) {
			internalConsole.reciveCall(2, "Found both a architecture and system model");
		}
		
		String[] cmdLine = {"java",  "-jar",  "C:\\temp\\JavaTest.jar", GlobalStorage.getArchModel(), GlobalStorage.getSysModel()};
		
		try {
			Process p = Runtime.getRuntime().exec(cmdLine);
			BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
			String line = null;
			while ((line = in.readLine()) != null) {
		    	internalConsole.reciveCall(2, line);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return null;
	}
	
	private IResource extractSelection(ISelection sel) {
		if (!(sel instanceof IStructuredSelection))
	    	return null;
		IStructuredSelection ss = (IStructuredSelection) sel;
		Object element = ss.getFirstElement();
		if (element instanceof IResource)
			return (IResource) element;
		if (!(element instanceof IAdaptable))
			return null;
		IAdaptable adaptable = (IAdaptable)element;
		Object adapter = adaptable.getAdapter(IResource.class);
		return (IResource) adapter;
	}
	
	private File[] findUMLFiles(File[] root) {
		String arch = "*Class*.uml";  //Should be something like *Arch_Model_*
		String sys = "*UseCase*.uml"; //Should be something like *Sys_Model_*
		FileFilter fileFilter = new FileFilter() {
			public boolean accept(File file) {
				return file.isFile();
			}
		}; 
		FileFilter dirFilter = new FileFilter() {
			public boolean accept(File file) {
				return file.isDirectory();
			}
		};
		
		for (File rootDir : root) {
		
			File[] projectFiles = rootDir.listFiles(fileFilter);
			if (projectFiles == null)
				return null;
			for (File projectFile : projectFiles) {
				if (finder.isStringMatching(projectFile.toString(), arch)) {
					GlobalStorage.setModelFlag(GlobalStorage.getModelFlag() + 1);					
					GlobalStorage.setArchModel(projectFile.toString());					
				}
				if (finder.isStringMatching(projectFile.toString(), sys)) {
					GlobalStorage.setModelFlag(GlobalStorage.getModelFlag() + 2);
					GlobalStorage.setSysModel(projectFile.toString());
				}
			}
			File[] projectSubDirectories = rootDir.listFiles(dirFilter);
			if (projectSubDirectories == null)
				return null;
			
			findUMLFiles(projectSubDirectories);
			
		}
		return null;
	}
	
}
